﻿namespace Pp.UI.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using Core;
    using Core.Extentions;
    using Dto;
    using Globalization;
    using Models;

    public class ProjectController : BaseController
    {
        [HttpPost, ValidateAntiForgeryToken]
        [Authorize]
        public JsonResult CreateComment(Guid? projectId, string comment)
        {
            var result = CommentRepository.NewComment(comment, projectId, User.Identity.Name);
            return Json(result);
        }

        [Authorize]
        public ActionResult New()
        {
            ViewData["Title"] = Res.Label_NewProject;

            return View(GetCreateViewModel());
        }

        private ProjectCreateViewModel GetCreateViewModel()
        {
            var viewModel = new ProjectCreateViewModel
            {
                Categories = new SelectList(ProjectCategoryRepository.GetAll(), "Id", "Name")
            };
            return viewModel;
        }
        [HttpPost, ValidateInput(false)]
        [Authorize]
        public ActionResult New(ProjectCreate createProject)
        {
            ViewData["Title"] = Res.Label_NewProject;
            if (ModelState.IsValid)
            {
                var result = ProjectRepository.NewProject(createProject, User.Identity.Name);
                if (result.Success)
                {
                    Flash(Res.Message_CreateProject_Success, MessageType.Success);
                    return RedirectToAction("Index", "Profile");
                }
            }
            return View(GetCreateViewModel());
        }
        [Authorize]
        public ActionResult Edit(Guid? id)
        {
            if (!id.HasValue)
                RedirectToAction("Index", "Profile");
            var dto = ProjectRepository.GetProjectEdit(id);
            var viewModel = new ProjectEditViewModel
            {
                ProjectDto = dto,
                Categories = new SelectList(ProjectCategoryRepository.GetAll(), "Id", "Name", dto.CategoryId)
            };
            ViewData["Title"] = Res.Title_Project_Edit;
            return View(viewModel);
        }
        [HttpPost, ValidateInput(false)]
        [Authorize]
        public ActionResult Edit(ProjectEdit projectEdit)
        {
            ViewData["Title"] = Res.Title_Project_Edit;
            if (ModelState.IsValid)
            {
                var result = ProjectRepository.EditProject(projectEdit, User.Identity.Name);
                if (result.Success)
                {
                    Flash(Res.Information_Edit_Project_Successfull, MessageType.Success);
                    return RedirectToAction("Index", "Profile");
                }
            }
            var viewModel = new ProjectEditViewModel
            {
                ProjectDto = projectEdit,
                Categories = new SelectList(ProjectCategoryRepository.GetAll(), "Id", "Name", projectEdit.CategoryId)
            };
            return View(viewModel);
        }
        [HttpGet]
        public ActionResult Detail(Guid? id)
        {
            if (!id.HasValue)
                return RedirectToAction("Index", "Profile");
            var detail = ProjectRepository.GetDetail(id);
            if (detail.Success)
            {
                ViewData["Title"] = detail.Data.Name.ToCrop(30);
                return View(new ProjectDetailViewModel()
                                {
                                    Detail = detail.Data,
                                    IsMyProject = (detail.Data.User.Username == User.Identity.Name)
                                });
            }
            Flash(detail.Error, MessageType.Failed);
            return RedirectToAction("Index", "Profile");
        }
        [HttpPost, ValidateAntiForgeryToken]
        [Authorize]
        public ActionResult Delete(Guid? id, string returnUrl)
        {
            if (string.IsNullOrEmpty(returnUrl)) return RedirectToAction("Index", "Home");
            var result = ProjectRepository.DeleteById(id);
            if (result.Success)
            {
                Flash(Res.Information_Drop_Project_Successfull, MessageType.Success);
            }
            else { Flash(result.Error, MessageType.Failed); }
            return Redirect(returnUrl);
        }
        [HttpPost, ValidateAntiForgeryToken]
        [Authorize]
        public ActionResult CommentDelete(Guid? id, string returnUrl)
        {
            if (string.IsNullOrEmpty(returnUrl)) return RedirectToAction("Index", "Home");
            var result = CommentRepository.DeleteById(id);
            if (result.Success)
            {
                Flash(Res.Information_Drop_Comment_Successfull, MessageType.Success);
            }
            else { Flash(result.Error, MessageType.Failed); }
            return Redirect(returnUrl);
        }
        public JsonResult Follow(FollowItem followItem)
        {
            var result = Result<int>.AsSuccess(0);
            if (followItem.FollowType == FollowType.Profile)
                result = ProfileFollowRepository.Follow(followItem.Id, User.Identity.Name);
            if (followItem.FollowType == FollowType.Project)
                result = ProjectFollowRepository.Follow(followItem.Id, User.Identity.Name);
            return Json(result);
        }
        public JsonResult CancelFollow(FollowItem followItem)
        {
            var result = Result<int>.AsSuccess(0);
            if (followItem.FollowType == FollowType.Profile)
                result = ProfileFollowRepository.CancelFollow(followItem.Id, User.Identity.Name);
            if (followItem.FollowType == FollowType.Project)
                result = ProjectFollowRepository.CancelFollow(followItem.Id, User.Identity.Name);
            return Json(result);
        }

        private string documentUrl = "/Content/Upload/Document/";
        public ActionResult GetFiles(Guid? id)
        {
            var infos = new List<string>();
            var path = documentUrl + id;
            var dir = Server.MapPath(path);
            if (Directory.Exists(dir))
            {
                var files = Directory.GetFiles(dir);
                infos.AddRange(files.Select(file => new FileInfo(file)).Select(fileInfo => path + "/" + fileInfo.Name));
            }
            return PartialView(infos);
        }
        private const string ProjImageUrl = "/Content/Upload/ProjectImage/";
        public ActionResult GetImages(Guid? id)
        {
            var infos = new List<string>();
            var path = ProjImageUrl + id;
            var dir = Server.MapPath(path);
            if (Directory.Exists(dir))
            {
                var files = Directory.GetFiles(dir);
                infos.AddRange(files.Select(file => new FileInfo(file)).Select(fileInfo => path + "/" + fileInfo.Name));
            }
            return PartialView(infos);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult Upload(UploadProject uploadProjectFile)
        {
            if (!ModelState.IsValid) return RedirectToAction("Index", "Home");
            if (!uploadProjectFile.Id.HasValue)
            {
                Flash("Proje yüklemesi için uygun proje bulunamıyor.", MessageType.Information);
                return RedirectToAction("Index", "Home");
            }
            var returnResult = RedirectToAction("Detail", "Project", new { Id = uploadProjectFile.Id });
            if (uploadProjectFile.File == null)
            {
                Flash("Yüklemek istediğiniz dosyayı seçiniz.", MessageType.Information);
                return returnResult;
            }
            if (!Directory.Exists(Server.MapPath(documentUrl)))
                Directory.CreateDirectory(Server.MapPath(documentUrl));
            var basePath = documentUrl + uploadProjectFile.Id.GetValueOrDefault();
            if (!Directory.Exists(Server.MapPath(basePath)))
                Directory.CreateDirectory(Server.MapPath(basePath));
            var fullPath = Server.MapPath(basePath + "/" + uploadProjectFile.File.FileName);
            if (System.IO.File.Exists(fullPath))
            {
                Flash("Aynı isimle bir dosya zaten bulunmaktadır.", MessageType.Information);
                return returnResult;
            }
            try
            {
                uploadProjectFile.File.SaveAs(fullPath);
            }
            catch (Exception)
            {
                Flash("Proje yüklemesi yapılamadı.", MessageType.Information);
                return returnResult;
            }
            Flash("Başarı ile yüklemeniz tamamlandı.", MessageType.Success);
            return returnResult;
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult UploadImage(UploadProject uploadProjectFile)
        {
            if (!ModelState.IsValid) return RedirectToAction("Index", "Home");

            var returnResult = RedirectToAction("Detail", "Project", new { uploadProjectFile.Id });

            var basePath = ProjImageUrl + uploadProjectFile.Id.GetValueOrDefault();
            try
            {
                var galleryRoot = Server.MapPath(basePath);
                var folderExists = Directory.Exists(galleryRoot);
                if (!folderExists)
                    Directory.CreateDirectory(galleryRoot);

                var file = galleryRoot + "/" + Guid.NewGuid() + ".jpg";
                if (System.IO.File.Exists(file))
                    System.IO.File.Delete(file);
                UserRepository.UploadImage(uploadProjectFile.File, ImageSize.gallerySize.Width, ImageSize.gallerySize.Height, file);
                Flash("Başarı ile yüklemeniz tamamlandı.", MessageType.Success);
            }
            catch (Exception)
            {
                Flash("Proje yüklemesi yapılamadı.", MessageType.Information);
                return returnResult;
            }

            return returnResult;
        }

    }
}
